package com.lark.web.service.impl;

import com.jcraft.jsch.Session;
import com.lark.common.exception.CustomException;
import com.lark.web.domain.Host;
import com.lark.web.service.DockerInstallService;
import com.lark.web.service.HostService;
import com.lark.web.ssh.service.SSHUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * fei
 */
@Slf4j
@Service
public class DockerInstallServiceImpl implements DockerInstallService {
    @Autowired
    private HostService hostService;


    @Override
    public String getHostSystemType(String ip) {
        String command = "hostnamectl | grep Operating\\ System";
        return execCommand(ip, command);
    }

    @Override
    public String addYumRepo(String ip, String repo) {
        String command = "yum-config-manager --add-repo " + repo;
        return execCommand(ip, command);
    }

    @Override
    public List<String> getDockerVersion(String ip) {
        List<String> versions = new ArrayList<>();
        String command = "yum list docker-ce --showduplicates | sort -r | awk '{split($2, a, \":\"); print a[2]}'";
        String response = execCommand(ip, command);
        if (StringUtils.isNotBlank(response)) {
            String[] split = response.split("\n");
            for (int i = 0; i < split.length; i++) {
                if (StringUtils.isNotBlank(split[i])) {
                    versions.add(split[i]);
                }
            }
        }
        return versions;
    }

    @Override
    public String install(String ip, String script) {
        String path = "/usr/local/";
        String command1 = "sudo tee " + path + "install_docker.sh <<-'EOF'" + script + "EOF";
        String res1 = execCommand(ip, command1);
        log.info("命令1 {}", res1);

        String command2 = "chmod +x " + path + "install_docker.sh";
        String res2 = execCommand(ip, command2);
        log.info("命令2 {}", res2);

        String command3 = "sh " + path + "install_docker.sh";
        String res3 = execCommand(ip, command3);
        log.info("命令3 {}", res3);

        return "";
    }

    private String execCommand(String ip, String command) {
        Host remoteHost = hostService.getEnalbeList(ip).get(0);
        if (Objects.isNull(remoteHost)) {
            throw new CustomException("请输入正确的IP");
        }

        Session session = SSHUtil.openSession(remoteHost.getHostIp(), 22, remoteHost.getAccount(),
                remoteHost.getPassword());
        log.info("执行命令：{}", command);
        String execResponse = SSHUtil.exec(session, command);
        return execResponse;
    }

}
